/*
 * This class will handle request in getting Meal information from Server
 * All the information would be wrapped in Meal Class object
 */

package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.configuration.Configuration;
import com.object.Meal;
import com.user.JSONParser;

public class MealFetch {

	//URL for fetching data
    private static String fetchMealByIdURL 	= "http://128.199.214.245/android/MealFetch/fetch_meal_by_id.php";
	private static String fetchAllMealURL 	= "http://128.199.214.245/android/MealFetch/fetch_all_meal.php";
	private static String fetchAllMealByRestaurantIdURL = "http://128.199.214.245/android/MealFetch/fetch_all_meal_by_restaurant_id.php";
	private static String fetchMealLikeByIdURL	= "http://128.199.214.245/android/MealFetch/fetch_meal_like_by_id.php";
	private static String searchMealURL	= "http://128.199.214.245/android/MealFetch/search_meal.php";
	
    //Keys for the Json field
    /*
     * KEY_STATUS shows the status of the request
     * 0 : Fail to get restaurant
     * 1 : Successfully in getting restaurant
     */
	private String KEY_STATUS 			= "STATUS";
	
	private String KEY_ID				= "ID";
	private String KEY_RESTAURANT		= "RESTAURANT";
    private String KEY_NAME 			= "NAME";
    private String KEY_DESCRIPTION 		= "DESCRIPTION";
    private String KEY_TAG				= "TAG";
    private String KEY_PICTURE 			= "PICTURE";
    private String KEY_PRICE			= "PRICE";
    private String KEY_RESULT			= "RESULT";
    private String KEY_NUMBER = "NUMBER";		//Returned by server telling how many restaurants 
    
    private String FAIL 	= "0";
    private String SUCCESS 	= "1";
    
    //For making httpRequest
    private JSONParser jsonParser;
    private JSONObject result;
    List<NameValuePair> params;
    
    //Constructor
    public MealFetch(){
        jsonParser = new JSONParser();
    }
    
    /*
	 * fetchMealById function will return an Meal object based on Meal id entered
	 * - non-null	: Data of the Meal with id = id
	 * - null		: No such Meal
	 */
	public Meal fetchMealById(int id){
		//Get Json object
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealById - Meal found");
					}
					
					// Store information to object
					int	restaurant			= Integer.parseInt(result.getString(KEY_RESTAURANT));
					String name 			= result.getString(KEY_NAME);
					String description 		= result.getString(KEY_DESCRIPTION);
					String tag				= result.getString(KEY_TAG);
					String picture		 	= result.getString(KEY_PICTURE);
					String price			= result.getString(KEY_PRICE);
					
					Meal meal = new Meal(id,restaurant,name,description,tag,picture,price);					
					
					return meal;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealById - Unable to find meal");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchMealById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchMealById - Exception");
			}
		}

		return null;
	}
	
	public List<Meal> fetchAllMeal(){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        //params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchAllMealURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal
					if(Configuration.showLog){
						Log.d("MealFetch","fetchAllMeal - Meal found");
					}
					
					int numberOfMeal = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <Meal> mealList = new ArrayList<Meal>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray restaurantArray		= result.getJSONArray(KEY_RESTAURANT);
					JSONArray nameArray 			= result.getJSONArray(KEY_NAME);
					JSONArray descriptionArray 		= result.getJSONArray(KEY_DESCRIPTION);
					JSONArray tagArray 				= result.getJSONArray(KEY_TAG);
					JSONArray pictureArray 			= result.getJSONArray(KEY_PICTURE);
					JSONArray priceArray 			= result.getJSONArray(KEY_PRICE);
					
					for(int i=0;i<numberOfMeal;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						int restaurant			= Integer.parseInt(restaurantArray.getString(i));
						String name 			= nameArray.getString(i);
						String description 		= descriptionArray.getString(i);
						String tag				= tagArray.getString(i);
						String picture 			= pictureArray.getString(i);
						String price			= priceArray.getString(i);
						
						Meal meal = new Meal(id,restaurant,name,description,tag,picture,price);
						mealList.add(meal);
						
					}
					
					return mealList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchAllMeal - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchAllMeal - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchAllMeal - Exception");
			}
		}
		return null;
	}
    
	public String fetchMealNameById(int id){
		//Get Json object
		// Building Parameters
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id",Integer.toString(id)));
		        
		//Start a new thread and use POST method to send telephone and passcode to authURL
		//Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
				
		while(attemptThread.isAlive()){
			//Wait for server response
		}
				
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealNameById - Meal found");
					}
							
					// Return the name of the restaurant
					return result.getString(KEY_NAME);
							
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealNameById - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchMealNameById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchMealNameById - Exception");
			}
		}

		return null;
	}
	
	/*
	 * This function will return a list of meals that are created by that restaurants
	 */
	public List<Meal> fetchAllMealByRestaurantId(int restaurant){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("restaurant",Integer.toString(restaurant)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchAllMealByRestaurantIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal
					if(Configuration.showLog){
						Log.d("MealFetch","fetchAllMealByRestaurantId - Meal found");
					}
					
					int numberOfMeal = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <Meal> mealList = new ArrayList<Meal>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray nameArray 			= result.getJSONArray(KEY_NAME);
					JSONArray descriptionArray 		= result.getJSONArray(KEY_DESCRIPTION);
					JSONArray tagArray 				= result.getJSONArray(KEY_TAG);
					JSONArray pictureArray 			= result.getJSONArray(KEY_PICTURE);
					JSONArray priceArray 			= result.getJSONArray(KEY_PRICE);
					
					for(int i=0;i<numberOfMeal;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						String name 			= nameArray.getString(i);
						String description 		= descriptionArray.getString(i);
						String tag				= tagArray.getString(i);
						String picture 			= pictureArray.getString(i);
						String price			= priceArray.getString(i);
						
						Meal meal = new Meal(id,restaurant,name,description,tag,picture,price);
						mealList.add(meal);
						
					}
					
					return mealList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchAllMealByRestaurantId - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchAllMealByRestaurantId - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchAllMealByRestaurantId - Exception");
			}
		}
		return null;
	}
	//Ryan: add

	/*
	 * This function will return a list of meals that are created by that restaurants
	 */
	public List<Meal> searchMeal(String inputName){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("inputName",inputName));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(searchMealURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}

		//Parse the json object
		try {
//			Log.d("Query", ("Query:inputName"+inputName));
//			Log.d("Query", ("Query:KEY_STATUS"+result.getString(KEY_STATUS)));

			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				Log.d("Query", ("Query:inputName"+inputName));

				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal

					if(Configuration.showLog){
						Log.d("MealFetch","searchMeal - Meal found");
					}
					
					int numberOfMeal = Integer.parseInt(result.getString(KEY_NUMBER));
					Log.d("MealFetch",Integer.toString(numberOfMeal));// for rice, i can get two

					List <Meal> mealList = new ArrayList<Meal>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					Log.d("MealFetch", ("Query:111"));
					JSONArray restaurantArray		= result.getJSONArray(KEY_RESTAURANT);
					JSONArray nameArray 			= result.getJSONArray(KEY_NAME);
					JSONArray descriptionArray 		= result.getJSONArray(KEY_DESCRIPTION);
					JSONArray tagArray 				= result.getJSONArray(KEY_TAG);
					JSONArray pictureArray 			= result.getJSONArray(KEY_PICTURE);
					JSONArray priceArray 			= result.getJSONArray(KEY_PRICE);
					
					for(int i=0;i<numberOfMeal;i++){
						// Store information to object
						

						int	id					= Integer.parseInt(idArray.getString(i));
						
						int restaurant			= Integer.parseInt(restaurantArray.getString(i));
						String name 			= nameArray.getString(i);
						String description 		= descriptionArray.getString(i);
						String tag				= tagArray.getString(i);
						String picture 			= pictureArray.getString(i);
						String price			= priceArray.getString(i);
						
						Meal meal = new Meal(id,restaurant,name,description,tag,picture,price);
						mealList.add(meal);
						
					}
					
					return mealList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","SearchMeal - Unable to search the meal");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","SearchMeal - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","SearchMeal - Exception");
			}
		}
		return null;
	}
	//Ryan: end
	/*
	 * This function will return a list of meals that are created by that restaurants
	 */
	public int fetchMealCountByRestaurantId(int restaurant){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("restaurant",Integer.toString(restaurant)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchAllMealByRestaurantIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealCountByRestaurantId - Meal found");
					}
					
					int numberOfMeal = Integer.parseInt(result.getString(KEY_NUMBER));
					
					return numberOfMeal;
					
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealCountByRestaurantId - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchMealCountByRestaurantId - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchMealCountByRestaurantId - Exception");
			}
		}
		return 0;
	}
	
	public int fetchMealLikeById(int id){
		//Get Json object
		// Building Parameters
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id",Integer.toString(id)));
				        
		//Start a new thread and use POST method to send telephone and passcode to authURL
		//Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealLikeByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
						
		while(attemptThread.isAlive()){
			//Wait for server response
		}
						
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealLikeById - Meal found");
					}
									
					// Return the name of the restaurant
					return Integer.parseInt(result.getString(KEY_NUMBER));
									
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealFetch","fetchMealLikeById - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealFetch","fetchMealLikeById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealFetch","fetchMealLikeById - Exception");
			}
		}
		return 0;
	}

}
